package com.example.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pt.dto.RecommendationFeedbackDTO;
import com.example.pt.entity.RecommendationFeedback;
import com.example.pt.mapper.RecommendationFeedbackMapper;
import com.example.pt.service.RecommendationFeedbackService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RecommendationFeedbackServiceImpl extends ServiceImpl<RecommendationFeedbackMapper, RecommendationFeedback> implements RecommendationFeedbackService {
    
    private static final Logger logger = LoggerFactory.getLogger(RecommendationFeedbackServiceImpl.class);

    @Override
    public boolean addFeedback(Integer userId, RecommendationFeedbackDTO feedbackDTO) {
        if (userId == null || feedbackDTO.getTorrentId() == null || feedbackDTO.getFeedbackType() == null) {
            logger.warn("添加反馈失败：参数不完整, userId={}, torrentId={}, feedbackType={}", 
                userId, feedbackDTO.getTorrentId(), feedbackDTO.getFeedbackType());
            return false;
        }
        
        logger.info("开始添加用户反馈: userId={}, torrentId={}, feedbackType={}, batchId={}", 
            userId, feedbackDTO.getTorrentId(), feedbackDTO.getFeedbackType(), feedbackDTO.getBatchId());
        
        // 检查是否已经提交过反馈
        if (checkUserFeedbackExists(userId, feedbackDTO.getTorrentId(), feedbackDTO.getFeedbackType())) {
            logger.info("用户 {} 已经对种子 {} 提交过类型 {} 的反馈，不重复记录", 
                userId, feedbackDTO.getTorrentId(), feedbackDTO.getFeedbackType());
            return true; // 已存在反馈，视为成功
        }
        
        try {
            RecommendationFeedback feedback = new RecommendationFeedback();
            feedback.setUserId(userId);
            feedback.setTorrentId(feedbackDTO.getTorrentId());
            feedback.setFeedbackType(feedbackDTO.getFeedbackType());
            feedback.setReason(feedbackDTO.getReason());
            feedback.setBatchId(feedbackDTO.getBatchId());
            feedback.setCreateTime(new Date());
            
            logger.debug("准备保存反馈记录: {}", feedback);
            boolean result = save(feedback);
            
            if (result) {
                logger.info("用户 {} 成功添加对种子 {} 的反馈，类型: {}", 
                    userId, feedbackDTO.getTorrentId(), feedbackDTO.getFeedbackType());
            } else {
                logger.warn("用户 {} 添加反馈失败, 数据库保存返回false", userId);
            }
            
            return result;
        } catch (Exception e) {
            logger.error("添加反馈时发生错误: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public List<Integer> getUserDislikedTorrentIds(Integer userId) {
        if (userId == null) {
            logger.warn("获取用户不感兴趣种子失败：用户ID为空");
            return List.of();
        }
        
        try {
            List<Integer> dislikedIds = baseMapper.getUserDislikedTorrentIds(userId);
            logger.debug("用户 {} 共有 {} 个不感兴趣的种子", userId, dislikedIds.size());
            return dislikedIds;
        } catch (Exception e) {
            logger.error("获取用户不感兴趣种子时发生错误: {}", e.getMessage(), e);
            return List.of();
        }
    }

    @Override
    public Map<Integer, Integer> getUserCategoryDislikeStats(Integer userId) {
        if (userId == null) {
            logger.warn("获取用户类别负反馈统计失败：用户ID为空");
            return Map.of();
        }
        
        try {
            List<Map<String, Object>> stats = baseMapper.getUserCategoryDislikeStats(userId);
            
            Map<Integer, Integer> result = new HashMap<>();
            for (Map<String, Object> stat : stats) {
                int category = ((Number) stat.get("category")).intValue();
                int dislikeCount = ((Number) stat.get("dislike_count")).intValue();
                result.put(category, dislikeCount);
            }
            
            logger.debug("用户 {} 的类别负反馈统计: {}", userId, result);
            return result;
        } catch (Exception e) {
            logger.error("获取用户类别负反馈统计时发生错误: {}", e.getMessage(), e);
            return Map.of();
        }
    }

    @Override
    public Map<Integer, Integer> countFeedbackTypesByTimeRange(Date startTime, Date endTime) {
        if (startTime == null || endTime == null) {
            logger.warn("统计反馈类型失败：时间参数不完整");
            return Map.of();
        }
        
        try {
            List<Map<String, Object>> stats = baseMapper.countFeedbackTypesByTimeRange(startTime, endTime);
            
            Map<Integer, Integer> result = new HashMap<>();
            for (Map<String, Object> stat : stats) {
                int feedbackType = ((Number) stat.get("feedback_type")).intValue();
                int count = ((Number) stat.get("count")).intValue();
                result.put(feedbackType, count);
            }
            
            logger.debug("时间段 {} 至 {} 的反馈类型统计: {}", startTime, endTime, result);
            return result;
        } catch (Exception e) {
            logger.error("统计反馈类型时发生错误: {}", e.getMessage(), e);
            return Map.of();
        }
    }

    @Override
    public boolean checkUserFeedbackExists(Integer userId, Integer torrentId, Integer feedbackType) {
        if (userId == null || torrentId == null || feedbackType == null) {
            return false;
        }
        
        try {
            int count = baseMapper.checkUserFeedbackExists(userId, torrentId, feedbackType);
            return count > 0;
        } catch (Exception e) {
            logger.error("检查用户反馈是否存在时发生错误: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean checkUserFeedbackExists(Integer userId, Integer torrentId) {
        if (userId == null || torrentId == null) {
            return false;
        }
        
        try {
            // 使用LambdaQueryWrapper代替直接调用Mapper
            LambdaQueryWrapper<RecommendationFeedback> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RecommendationFeedback::getUserId, userId)
                      .eq(RecommendationFeedback::getTorrentId, torrentId);
            
            // 查询记录数
            long count = count(queryWrapper);
            return count > 0;
        } catch (Exception e) {
            logger.error("检查用户反馈是否存在时发生错误: {}", e.getMessage(), e);
            return false;
        }
    }
} 